<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" />
        <title>🌤️sun water7000</title>
        <style>
            button:hover{
                color:mediumseagreen;
                /*brightness(1.3); */
                /* %% for python */
                filter:invert(200%);
            }
            .update{
                font-size: 1.2rem;
            }
            .water{
                background: rgba(0, 132, 255, 0.884);
            }
            .t{
                background: rgba(226, 75, 55, 0.781);
            }
            .f5{
                color:green;
                border:1px dashed;
                background:rgb(223, 212, 250);
            }
            .history{
                color:white;
                background:burlywood;
                border:1px dashed;
                display: none;
            }
            .clicked{
                color:white;
                background: rgba(85, 85, 85, 0.781);
            }
            .row{
                display: block;
            }
            .auto_heat{
                font-size: 1.2rem;
            }
        </style>
    </head>
    <body> 
    <h1 id="title">sun_water</h1>
    <div id="f5" class="f5">
    刷新🔄️
    </div>
    <div id="history" class="history">
    历史🎖️
    </div>
    <div>
        时间= <span id="now"></span><br/>
        <span style="color:blue">水位= <span id="h"></span> <span id="h_on"></span></span><br/>
        <span style="color:red">水温= <span id="t"></span>℃ <span id="t_on"></span></span><br/>
    </div>

    <div id="hiden" style="display:none">
        info="/sun_water_info.json"
        <br/>
        <button class="update water" url="/sun_water_feed">上水(2|3格)</button>|
        <button class="update water" url="/sun_water_full_feed">上水4格</button><br>
        <button class="update" url="/sun_water_cancel_feed">取消上水</button>
        <br/>
        <button class="update t" url="/sun_water_heat">加热(65℃)</button>|
        <button class="update t" url="/sun_water_heat75">加热到75℃</button><br>
        <button class="update" url="/sun_water_cancel_heat">取消加热</button>
        <br/>
        <span id="get_state_auto_heat">auto_heat:每天的定时自动加热</span><br/>
        <span style="color:orange"><span id="auto_heat"></span></span><br/>
        <button class="auto_heat" url="/turn_on_auto_heat">turn_on</button>
        <button class="auto_heat" url="/turn_off_auto_heat">turn_off</button>
        <br/>
        <br/>
        <button class="update" url="/reset_system">reset重启</button>
        <div>
            <ul id="data"></ul>
        </div>
    </div>
    <script>
        const calc =()=>{
            let d = document.documentElement;
            let w=d.clientWidth;
            let h=d.clientHeight;
            let w2 = w > 750 ? 750 : w;
            if(w2>d.clientHeight){
                w2=parseInt(h*3/4);
            }
            d.style.fontSize = 20 * (w2 / 375) + 'px';
        }
        calc();
        window.addEventListener('resize', calc);
    </script>
    <script>
        function log(...s){
            console.log(...s);
        }
        const ROOT_URLs=["",
            "http://sun_water70000.esp32.lan",
            "http://sun_water70001.esp32.lan"
        ];
        let ROOT_URL="";
        let founds=[];
        let ROOT_URL_HAS_FOUND=false;
        for(let i=0;i<ROOT_URLs.length;i++){
            let u0=ROOT_URLs[i];
            let u=u0+"/ping";
            fetch(u).then((res)=>{
                return res.json();
            }).then(obj=>{
                if(obj&&obj.code){
                    if(obj.code=="OK"&&obj.action=="ping"){
                        ROOT_URL=u0;
                        founds.push(u0);
                        for(let j in founds){
                            let found=founds[j];
                            if(found==""){
                                // "" 优先
                                ROOT_URL="";
                            }
                        }
                        ROOT_URL_HAS_FOUND=true;
                        log("[i] found ROOT_URL=",u0)
                    }
                }
            }).catch(e=>{

            })
        }

        const get_URL=(u)=>{
            if(u.startsWith("http://")){
                return u;
            }
            if(u.startsWith("https://")){
                return u;
            }
            return ROOT_URL+u;
        }

        let q=(s)=>document.querySelector(s);
        let g=(c,n,m)=>{
            n=parseInt(n);
            let r="("+n+")";
            if(Number.isNaN(n) || n<0){
                n=0;
            }
            for(let i=0;i<n;i++){
                r+=c;
            }
            m=m-n;
            if(Number.isNaN(m)){
                m=4;
            }
            for(let i=0;i<m;i++){
                r+="_";
            }
            return r;
        }

        let ss=(o,s)=>{
            o.innerText=s;
        }

        let set_clicked=(target,timeout=1000)=>{
            target.classList.add("clicked");
            setTimeout(()=>{
                target.classList.remove("clicked");
            },timeout);
        }
        
        let f5=q("#f5");
        let history=q("#history");
        let data=q("#data");
        let hiden=q("#hiden");
        let now=q("#now");
        let t=q("#t");
        let t_on=q("#t_on");
        let h=q("#h");
        let h_on=q("#h_on");
        let auto_heat=q("#auto_heat");
        let title=q("#title");

        let HOUR=-1;
        
        let showHiden=(turnon=true)=>{
            if(turnon){
                hiden.style.display="block";
                history.style.display="block";
            }else{
                hiden.style.display="none";
                history.style.display="none";
            }
        }
        let showDetail=localStorage.getItem("showDetail");
        if(showDetail){
            showHiden(true);
        }

        let showInfo=(obj)=>{
            let html="";
            for(let i in obj){
                html+="<li>"+i+":"+obj[i]+"</li>";
            }
            data.innerHTML=html;
        }

        let mk_tb=(obj)=>{
            let out='<table border="1">';
            for(let row in obj){
                let tr=`<tr>`;
                for(let col in obj[row]){
                    tr=`${tr}<td>${obj[row][col]}</td>`;
                }
                out=out+tr+"</tr>";
            }
            out=out+"</table>";
            return out;
        }

        let showHistory=(obj)=>{
            if(!obj){
                return
            }
            let time=obj.latest_heating||"";
            let html="<li>latest_heating time:</li><li>"+time+"</li>";
            html+="<li>hour, minute, t, target_t, h, target_h</li>";

            let gen=(i="yestoday",now=23)=>{
                html+="<li>"+i+":"+"</li>";
                html+="<li>"+mk_tb(obj[i])+"</li>";
            }

            if(obj["yestoday"]==-1){
                gen("today",HOUR);
            }else{
                let i="today";
                html+="<li>"+i+":"+"</li>";
                html+="<li>"+mk_tb(obj[i])+"</li>";
                gen();
            }
            data.innerHTML=html;
        }

        let count=0;
        title.onclick=()=>{
            count++;
            if (count>=5){
                if(count==5){
                    let showDetail=localStorage.getItem("showDetail");
                    if(showDetail){
                        showHiden(false);
                        localStorage.removeItem("showDetail")
                    }else{
                        showHiden(true);
                        localStorage.setItem("showDetail","showDetail")
                    }
                    setTimeout(()=>{
                        count=0;
                    },1000)
                }
            }
        };
        run=(obj)=>{
            if(obj.temperature!==undefined&&obj.temperature!==null){
                HOUR=parseInt(obj.time.split(":")[0]);
                let temperature=obj.temperature_float||obj.temperature;
                ss(now,obj.time);
                ss(t,temperature);
                ss(t_on, obj.heating=="ON"? "[↑"+obj.target_t+"]":"");
                ss(h, g("Y",obj.height,4));
                ss(h_on, obj.feeding=="ON"? "[↑"+obj.target_h+"]":"");
            }
            showInfo(obj);
        };
        run_url=(u,func=run)=>{
            fetch(u).then(r => r.json()).then(d=>func(d)).catch((e)=>{
                log("[E] fetch error",e);
            });
        }

        let u="/sun_water_info.json";
        let get_info=()=>{
            let u2=get_URL(u);
            log("[i] fetch info:",u2);
            set_clicked(f5,1500);
            run_url(u2);
        }
        setTimeout(()=>get_info(),1000);
        f5.onclick=()=>{
            get_info();
        }

        document.querySelectorAll("button.update").forEach(v=>{
            v.addEventListener("click",(e)=>{
                e.preventDefault();
                let u=e.target.getAttribute("url");
                if(u){
                    u=get_URL(u);
                    log(u);
                    set_clicked(e.target,1500);
                    run_url(u);
                }
            })
        })
        history.addEventListener("click",(e)=>{
            e.preventDefault();
            let u="/sun_water_history";
            if(u){
                u=get_URL(u);
                log(u);
                set_clicked(e.target,1500);
                run_url(u,showHistory);
            }
        })
        document.querySelectorAll("button.auto_heat").forEach(v=>{
            v.addEventListener("click",(e)=>{
                e.preventDefault();
                let u=e.target.getAttribute("url");
                if(u){
                    u=get_URL(u);
                    log(u);
                    fetch(u).then(resp=>{
                        return resp.text();
                    }).then(
                        text=>{
                            log(text);
                            auto_heat.innerText=text;
                            get_state_auto_heat();
                            try{
                                log(JSON.parse(text));
                            }catch{

                            }
                        }
                    ).catch(e=>{
                        auto_heat.innerText="??";
                        log(e);
                    });
                }
            })
        })

        let handler1;
        function get_state_auto_heat(callback){
            fetch(get_URL("/get_state_auto_heat")).then((r)=>{
                    return r.text();
                }).then((data)=>{
                    log(data);
                    try{
                        let obj=JSON.parse(data);
                        if(obj){
                            log(obj);
                            if(obj.value){
                                obj=JSON.parse(obj.value);
                                // state::agent=False;saved=false
                                let state=obj.state.agent.toLowerCase();
                                let state2=obj.state.saved.toLowerCase();
                                if(state==state2){
                                    auto_heat.innerText=state;    
                                }else{
                                    auto_heat.innerText=`agent=${state},saved=${state2}`;
                                }
                            }
                        }
                    }catch(e){
                        log(e);
                        auto_heat.innerText=data;
                    }
                    
                    
                    if(callback){
                        callback();
                    }
                })
        };
        q("#get_state_auto_heat").addEventListener("click",(e)=>{
            get_state_auto_heat();
        });

        handler1=setInterval(()=>{
            if (ROOT_URL_HAS_FOUND){
                get_state_auto_heat(()=>{
                    clearInterval(handler1);
                });
            }
        },5000)
        setTimeout(()=>{
            if (ROOT_URL_HAS_FOUND){
                get_state_auto_heat(()=>{
                    clearInterval(handler1);
                });
            }
        },500);
    </script>
    </body>
</html>

